package id.web.zaniar.oraboros;

//Type that contains event's type-listener pair
typedef EventHandler = {
    var type : String;
    var listener : Dynamic -> Void;
}

class GameState extends flash.display.MovieClip {
    //List of type-listener pairs
    private var eventHandlers : List<EventHandler>;

    //Constructor
    public function new() {
        super();
        eventHandlers = new List<EventHandler>();
    }

    //Add event listener to the state
    public function addEvent(type : String, listener : Dynamic -> Void) {
        var eventHandler : EventHandler = {type : type, listener : listener};

        eventHandlers.push(eventHandler);
    }

    //Remove event listener from the state
    public function removeEvent(type : String, listener : Dynamic -> Void) {
        var eventHandler : EventHandler;

        for(eventHandler in eventHandlers.iterator()) {
            if(eventHandler.type == type && eventHandler.listener == listener) {
                eventHandlers.remove(eventHandler);
                break;
            }
        }
    }

    //Activate the state
    public function activate() {
        flash.Lib.current.addChild(this);

        for(i in eventHandlers.iterator()) {
            this.stage.addEventListener(i.type, i.listener);
        }
    }

    //Deactivate the state
    public function deactivate() {
        for(i in eventHandlers.iterator()) {
            this.stage.removeEventListener(i.type, i.listener);
        }

        flash.Lib.current.removeChild(this);
    }
}
